<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div>
    <button id="btn1">按钮1</button>
    <button id="btn2">按钮2</button>
    <button id="btn3">按钮3</button>
  </div>


  <script>
    var btn1 = document.getElementById('btn1')
    var btn2 = document.getElementById('btn2')
    var btn3 = document.getElementById('btn3')

    // 定义一个命令发布者(执行者)的类
    class Executor {
      setCommand(btn, command) {
        btn.onclick = function () {
          command.execute()
        }
      }
    }

    // 定义一个命令接收者
    class Menu {
      refresh() {
        console.log('刷新菜单')
      }

      addSubMenu() {
        console.log('增加子菜单')
      }
    }

    // 定义一个刷新菜单的命令对象的类
    class RefreshMenu {
      constructor(receiver) {
        // 命令对象与接收者关联
        this.receiver = receiver
      }

      // 暴露出统一的接口给命令发布者Executor
      execute() {
        this.receiver.refresh()
      }
    }

    // 定义一个增加子菜单的命令对象的类
    class AddSubMenu {
      constructor(receiver) {
        // 命令对象与接收者关联
        this.receiver = receiver
      }
      // 暴露出统一的接口给命令发布者Executor
      execute() {
        this.receiver.addSubMenu()
      }
    }

    var menu = new Menu()
    var executor = new Executor()

    var refreshMenu = new RefreshMenu(menu)
    // 给按钮1添加刷新功能
    executor.setCommand(btn1, refreshMenu)

    var addSubMenu = new AddSubMenu(menu)
    // 给按钮2添加增加子菜单功能
    executor.setCommand(btn2, addSubMenu)

        // 如果想给按钮3增加删除菜单的功能，就继续增加删除菜单的命令对象和接收者的具体删除方法，而不必修改命令对象
  </script>
</body>

</html>